<?php
namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Db;

class DbBackup extends Command
{
    protected static $defaultName = 'db:backup';
    
    protected function configure()
    {
        $this->setDescription('Backup database structure and data');
    }
    
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            // 确保备份目录存在
            $backupDir = base_path() . '/database';
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }

            // 获取所有表
            $tables = Db::query('SHOW TABLES');
            $backup = [];
            
            foreach ($tables as $table) {
                $tableName = array_values($table)[0];
                
                // 获取建表语句
                $createTable = Db::query("SHOW CREATE TABLE `$tableName`")[0];
                $createSql = $createTable['Create Table'];
                
                // 获取表数据
                $rows = Db::table($tableName)->select()->toArray();
                
                $backup[$tableName] = [
                    'structure' => $createSql,
                    'data' => $rows
                ];
            }
            
            // 保存备份文件
            $backupFile = $backupDir . '/backup_' . date('Y_m_d_His') . '.php';
            file_put_contents($backupFile, '<?php return ' . var_export($backup, true) . ';');
            
            $output->writeln("<info>Database backup created at: $backupFile</info>");
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $output->writeln("<error>Backup failed: {$e->getMessage()}</error>");
            return Command::FAILURE;
        }
    }
} 